package com.ruoyi.kenuo.netty;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * netty  服务器
 */
public class NettyServer {

    //ConcurrentHashMap是线程安全的
    public static final Map<String, Channel> USERS = new ConcurrentHashMap<>(1024);
    public static final ChannelGroup GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);



    public static void start() {
        //创建线程池 主线程池
        EventLoopGroup boss = new NioEventLoopGroup();
        //创建工作线程 从线程池
        EventLoopGroup worker = new NioEventLoopGroup();

        //绑定端口
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss,worker)//将线程放入线程池
                .channel(NioServerSocketChannel.class) //选择NIO的channel类型
                .childHandler(new ChannelInitializer<SocketChannel>(){

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new HttpServerCodec()) //http解码器
                                .addLast(new ChunkedWriteHandler()) //支持写大数据流
                                //对http消息做聚合操作，会产生FullHttpRequest、FullHttpResponse http聚合器
                                .addLast(new HttpObjectAggregator(1024 * 64))
                                //websocket支持
                                .addLast(new WebSocketServerProtocolHandler("/")) //websocket的根路径
                                .addLast(new WebSocketHandler());//自定义websocket处理类
                    }
                });

        //绑定Netty的启动端口
        ChannelFuture future = bootstrap.bind(8888);
    }

    public static void main(String[] args) {
        NettyServer.start();
    }


}
